const db = uniCloud.database()
const dbCmd = db.command
module.exports = {
	defaultAddress(userId) {
		return db.collection('user-address').limit(1).where({
			user_id: userId,
			is_default: true
		}).get()
	},
	// 用户领取优惠卷
	async getCoupon(user_id, coupon_id) {
		// 先看一下是否存在该用(后期验证用户token是否正确)
		// 检查差传递过来的用户id和优惠券id是否有问题
		let userGet = await db.collection('uni-id-users').doc(user_id).get();
		if (userGet.data.length > 0) {
			// 看一下这个优惠券是否可以领取
			let couponGet = await db.collection('coupon').where({
				_id: coupon_id,
				available: dbCmd.gt(0)
			}).get();
			
			if (couponGet.data.length > 0) {
				console.log(couponGet.data)
				// 领取优惠券
				let data = couponGet.data[0];
				let now = Date.now()
				let userCouponAdd = await db.collection('user-coupon').add({
					user_id: user_id,
					coupon_id: data._id,
					reason: data.reason,
					valuedesc: data.valuedesc,
					condition: data.condition,
					name: data.name,
					start: data.start,
					end: data.end,
					value: data.value,
					gettime: now,
					use: false
				});
				// 领完优惠券 优惠券库存数量减少一个
				if (userCouponAdd) {
					db.collection('coupon').where({
						_id: coupon_id,
						available: dbCmd.gt(0)
					}).update({
						available:dbCmd.inc(-1)
					})
				}
				return {
					code:0,
					errMsg:"领取成功",
					data:userCouponAdd
				}
			} else {
				return {
					code: 1,
					errMsg: "优惠券数量不足"
				}
			}
			// 看一下是否该用户已经领取过这个优惠券了
		} else {
			return {
				code: 1,
				errMsg: "没有该用户"
			}
		}

	},
	async money(userId) {
		let resUser = await db.collection('uni-id-users').limit(1).where({
			_id: userId
		}).get();
		return {
			affectedDocs: resUser.affectedDocs,
			data: {
				money: resUser.data[0].money
			}
		}
	},
	async addressList(userId) {
		let list = await db.collection('user-address').where({
			user_id: userId
		}).get();
		list.defaultId = "";
		for (let i = 0; i < list.data.length; i++) {
			const elem = list.data[i];
			list.data[i].id = elem._id
			list.data[i].tel = elem.mobile
			list.data[i].address = elem.formatted_address
			list.data[i].isDefault = elem.is_default
			if (elem.is_default) {
				list.defaultId = elem._id
			}
		}
		return list
	},
	async setAddressDefault(Id, userId) {
		let adrDB = db.collection('user-address')
		// 大家自己完成更新默认地址
		// ERROR userId->user_id
		let update = await adrDB.where({
			user_id: userId
		}).update({
			is_default: false
		})
		let def = await adrDB.where({
			user_id: userId,
			_id: Id
		}).update({
			is_default: true
		})
		return def;
	}

}
